package oauth2_demon.servlet.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oauth2_demon.servlet.JsonMsg;
import oauth2_demon.servlet.Oauth2Api;
import oauth2_demon.servlet.User;
import oauth2_demon.servlet.UserApi;

import org.apache.commons.lang.StringUtils;

/**
 * Servlet implementation class TokenServlet
 */
public class TokenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static ConcurrentHashMap<Long, String> Users;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TokenServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
		String code = request.getParameter("code");
		
		//根据oschina authorization_code 回调的code请求 access_token
				String access_token= Oauth2Api.getAccess_token(code);
				System.out.println("access_token = "+access_token);
				if(StringUtils.isBlank(access_token)){//授权码获取失败
					JsonMsg.json_out(JsonMsg.jsonError("access_token获取失败"),response);
					return;
				}
				
				//根据access_token 获取User
				User user = UserApi.getUser(access_token);
				if(null == user || !StringUtils.isNumeric(user.getId())){
					JsonMsg.json_out(JsonMsg.jsonError("user获取失败"),response);
					return;
				}
				request.getSession().setAttribute("access_token", access_token);
				
				Users().put(Long.valueOf(user.getId()), access_token);
				
		        Cookie u = new Cookie("user",user.getId()) ;
		        u.setMaxAge(600) ;
		        u.setPath("/") ;
		        String userhref = user.getUrl();
		        Cookie linkcookie = new Cookie("href",userhref) ;
		        linkcookie.setMaxAge(600) ;    
		        linkcookie.setPath("/") ;
		        Cookie username = new Cookie("username",URLEncoder.encode(user.getName(),"UTF-8")) ;
		        username.setMaxAge(600) ;    
		        username.setPath("/") ;
		        response.addCookie(u) ;
				RequestDispatcher rd = request.getRequestDispatcher( "/index.html"); 
				rd.forward(request, response);

//		        JsonMsg.json_out("{'access_token':'"+access_token+"'}", response);
		        
		        
	}
	
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		Users = new ConcurrentHashMap<Long,String>();
		super.init(config);
	}
	public static ConcurrentHashMap<Long, String> Users(){
		if(Users==null){
			Users = new ConcurrentHashMap<Long,String>();
		}
		return Users;
	}

}
